var continue_type = '';
jQuery(document).ready(function() {
  $("[id='title']").each(function(){
    $(this).hover(function(){
        $(this).next('.tipdiv').show();
        },function(){
        $(this).next('.tipdiv').fadeOut(1000);
      });
  });
  $("#search_title").keyup(function(event){
    if(event.keyCode == 13){
      search_handle();
      return false;
    }
  });
  $("#search_tip").click(function() {
    search_handle();
  });
  $("#proj_title").click(function() {
    get_project_list_by_order("title");
  });
  $("#proj_updated").click(function() {
    get_project_list_by_order("updated");
  });
  $("#proj_created").click(function() {
    get_project_list_by_order("created");
  });
  $("#project_status_selector").change(function() {
    var query_status_selected = $(this).find("option:selected").val();
    url = "/mysurvey";
    if("all" != query_status_selected) {
      url += "?status=" + query_status_selected;
    }
    window.location.href = url;
  });
  $(".deletebtn").click(function() {
    var proj_id = $(this).attr("pid");
    var $form = $("#form1");
    $form.attr("action", "/edit/ajax/del_project");
    $form.attr("callback", "del_project_callback");
    $form.find('input[name="proj_id"]').val(proj_id);
    var show_txt = '<a class="jsbox_close" title="关闭" href="javascript:void(0)"></a>';
    show_txt += '<span style="color:red">你要删除这份问卷吗？删除后无法恢复</span>';
    var confirm_popup_win = Object();
    confirm_popup_win.title = "删除问卷确认";
    confirm_popup_win.content = show_txt;
    confirm_popup_win.obj = del_project_func;
    jsConfirm(confirm_popup_win);
  });
  
  $(".color").click(function() {
    var proj_id = $(this).attr("pid");
    rspd_count = $("#rspd_count_"+proj_id).text();
    if(rspd_count != 0)
    {
      continue_type = 'clear_data';
      cur_design_obj = $(this);
      var confirm_popup_win = Object;
      confirm_popup_win.title = '清空问卷确认';
      var content = "您的问卷已收集"+rspd_count+"份答卷数据，";
      content += "确定清空吗？";
      confirm_popup_win.content = content;
      confirm_popup_win.obj = clear_rspd_data;
      confirm_popup_win.conw = 300;
      // confirm_popup_win.close_obj = continue_design_project;
      jsConfirm(confirm_popup_win);
    }
  });
  // $(".jsbox_close").live('click',function(){
  //   status_changed_cancle();
  // });
  for(var i=0;i<func_list.length;i++)
  {
    func_options += '<option value="' + func_list[i].value + '">' + func_list[i].name + '</option>';
  }
  $(".copysurvey").live('click',function() {
    var proj_id = $(this).attr("pid");
    var status_selector = $(this).parent().prev().prev().children(0);
    if(status_selector.val() == 2) {
      $("#proj_copy_form").find('input[name="proj_id"]').val(proj_id);
      var func_id = $(this).attr("fid");
      $("#proj_copy_form").find('input[name="func_id"]').val(func_id);
      var title = $(this).parent().parent().children().eq(0).text() + "-副本";
      var show_txt = '<h2 class="jsboxTitle">复制问卷</h2><a class="jsbox_close" title="关闭" href="javascript:void(0)"></a>';
      show_txt += '<div><div class="copyconfirm"><div class="alertdiv"><table><tr>';
      show_txt += '<td width="90" class="alignr">新问卷标题：</td><td><input type="text" id="proj_copy_title" class="btx" value="' + title + '"/>';
      show_txt += '</td></tr><tr><td class="alignr">类别：</td><td><select id="proj_copy_func_id" func_id="' + func_id + '">' + func_options + '</select></td></tr>';
      show_txt += '<tr><td></td><td><div class="WJButton wj_blue smallfontsize mtop13 tcQz">创 建</div></td></tr>';
      show_txt += '</table></div></div></div>';

      proj_copy_confirm('400', show_txt, proj_copy_submitter, $(this).attr("fid"));
    }
  });

  $(".copysurvey2").live('click',function() {
    var proj_id = $(this).attr("pid");
    var status_selector = $(this).parent().prev().prev().children(0);
      $("#proj_copy_form").find('input[name="proj_id"]').val(proj_id);
      var func_id = $(this).attr("fid");
      $("#proj_copy_form").find('input[name="func_id"]').val(func_id);
      var title = $(this).parent().parent().children().eq(0).text() + "-副本";
      var show_txt = '<h2 class="jsboxTitle">复制问卷</h2><a class="jsbox_close" title="关闭" href="javascript:void(0)"></a>';
      show_txt += '<div><div class="copyconfirm"><div class="alertdiv"><table><tr>';
      show_txt += '<td width="90" class="alignr">新问卷标题：</td><td><input type="text" id="proj_copy_title" class="btx" value="' + title + '"/>';
      show_txt += '</td></tr><tr><td class="alignr">类别：</td><td><select id="proj_copy_func_id" func_id="' + func_id + '">' + func_options + '</select></td></tr>';
      show_txt += '<tr><td></td><td><div class="WJButton wj_blue smallfontsize mtop13 tcQz">创 建</div></td></tr>';
      show_txt += '</table></div></div></div>';

      proj_copy_confirm('400', show_txt, proj_copy_submitter, $(this).attr("fid"));
  });

});

function del_project_func(){
  ajaxSubmit($("#form1"));
}
//提示
function search_handle(){
  var search_txt = $("#search_title").val().trim();
  if("" == search_txt) {
    loadMack({off:'on',Limg:0,text:'请输入问卷标题',set:1500});
    $("#search_title").focus();
    return;
  }
  window.location.href = encodeURI("/mysurvey?search_txt=" + search_txt);
}
function proj_copy_confirm(conw, show_txt, obj, func_id) {
  var wb = new jsbox({
    onlyid: "maptss",
    conw: conw,
    //FixedTop:170,
    content: show_txt,
    range: true,
    mack: true
  }).show();
  var func_id = $("#proj_copy_func_id").attr("func_id");
  $("#proj_copy_func_id").children().each(function() {
    if(func_id == $(this).val()) {
      $(this).attr("selected", "selected");
      return;
    }
  });

  $('.tcQz').one('click', function() {
    $("#proj_copy_form").find('input[name="proj_title"]').val($("#proj_copy_title").val());
    $("#proj_copy_form").find('input[name="func_id"]').val($("#proj_copy_func_id").val());
    obj();
  });
}

function proj_copy_submitter() {
  var $form = $("#proj_copy_form");
  var title = $form.find('input[name="proj_title"]').val();
  if(title.trim() == "") {
    alert("请输入新问卷标题！");
    return;
  }
  var func_id = $form.find('input[name="func_id"]').val();
  ajaxSubmit($form);
}

function survey_copy_callback(resultJson) {
  window.location.href = "/edit/survey/" + resultJson.proj_id + "";
}

function get_project_list_by_order(fld) {
  var cls_order = $("#proj_" + fld).attr("class");
  var query_status_selected = $("#project_status_selector").find("option:selected").val();
  var url = "/mysurvey?fld=" + fld
  if(cls_order == "sequencedown") {
    if("all" != query_status_selected) {
      url += "&status=" + query_status_selected;
    }
  } else {
    if("all" != query_status_selected) {
      url += "&status=" + query_status_selected + "&ord=asc";
    } else {
      url += "&ord=asc";
    }
  }
  var search_txt = $("#search_title").val().trim();
  if("" != search_txt) {
    url += "&search_txt=" + search_txt;
  }
  window.location.href = encodeURI(url);
}

function action_submitter() {
  ajaxSubmit($("#form1"));
}
//提示


function jsConfirm(conw, show_txt, obj, Param) {
  var wb = new jsbox({
    onlyid: "maptss",
    conw: conw,
    //FixedTop:170,
    content: show_txt,
    range: true,
    mack: true
  }).show();

  $('.tcQz').one('click', function() {
    if(!Param) Param = '';
    obj(Param);
  });
  $('.uniteC').one('click', function() {
    $('.jsbox_close').click();
  });
}

var param_obj_for_status = "";

function proj_status_changed(obj) {
  var status = $(obj).val();
  var proj_id = $(obj).attr("pid");
  var proj_title = $(obj).parent().parent().children().eq(0).text();
  var lastv = $(obj).attr("lastv");
  var pop_win_title = "";
  var pop_win_content = "";
  var $form = $("#form1");
  $form.attr("action", "/edit/ajax/update_project_status/");
  $form.find('input[name="proj_id"]').val(proj_id);
  $form.find('input[name="status"]').val(status);
  var show_txt = "";
  if(status == 0) {
    pop_win_title = "停止发布确认";
    pop_win_content += '<a class="jsbox_close" title="关闭" href="javascript:void(0)"></a>';
    pop_win_content += '你要停止发布问卷《' + proj_title + '》吗？';
    pop_win_content += '该问卷所有数据收集将被止，答卷链暂时关闭。';

  } else if(status == 1) {
    pop_win_title = "发布问卷确认";
    var is_shared = $(obj).attr("is_shared");
    var copy_from_pid = $(obj).attr("copy_from_pid");
    var panelsite = $(obj).attr("panelsite");
    pop_win_content += '<a class="jsbox_close" title="关闭" href="javascript:void(0)"></a>';
    pop_win_content += '你要发布问卷《' + proj_title + '》吗？<br/>';
    if(is_shared == 0 && copy_from_pid == 'False'&& panelsite != '3') {
      pop_win_content += '<label><input type="checkbox" checked="checked" id="checkbox_selector"/>共享到模板库。</label>';
      pop_win_content += '<i class="tips" title="选中该选项，本问卷经审核合格后会添加到问卷库中，供其他会员制作问卷时参考。"></i>';
    }
  } else {
    pop_win_title = "结束问卷确认";
    pop_win_content += '<a class="jsbox_close" title="关闭" href="javascript:void(0)"></a>';
    pop_win_content += '你要结束问卷《' + proj_title + '》吗？';
    pop_win_content += '已结束的问卷将不可再编辑和收集。';
    pop_win_content += '如果想要重新收集，你可以将该问卷复制成一份新的问卷重新发布。';
  }
  param_obj_for_status = $(obj);
  status_changed_confirm(pop_win_title,pop_win_content,status_changed_ok,status_changed_cancle);
}

function status_changed_confirm(title, content, ok_func, cancle_func){
  var confirm_popup_win = Object();
  confirm_popup_win.title = title;
  confirm_popup_win.content = content;
  confirm_popup_win.obj = ok_func;
  confirm_popup_win.close_obj = cancle_func;
  jsConfirm(confirm_popup_win);
}

function status_changed_ok(){
  var is_shared = $(param_obj_for_status).attr("is_shared");
    if(is_shared == 0) {
      var status = $(param_obj_for_status).val();
      if(status == 1) {
        if("checked" == $("#checkbox_selector").attr("checked")) {
          var $form = $("#form1");
          $form.find('input[name="is_shared"]').val("checked");
        }
      }
    }
    ajaxSubmit($("#form1"));
}
function status_changed_cancle(){
    var sel_index = $(param_obj_for_status).attr("lastv");
    $(param_obj_for_status).get(0).selectedIndex = sel_index;
    $('#maptss').remove();
    $('#lightBox').remove();
}
var cur_design_obj;
function project_design_confirm(obj)
{
  cur_design_obj = obj;
  $("#get_rspd_count_form input[name='proj_id']").val($(obj).attr("pid"));
  ajaxSubmit($("#get_rspd_count_form"));
}

function pget_rspd_count_callback(info){
  //有答卷数据需确认，没有的话直接跳转答卷设计
  if(info.rspd_count != 0 || info.new_rspd_count != 0)
  {
    if(info.new_rspd_count != 0)
    {
      var confirm_popup_win = Object;
      confirm_popup_win.title = '修改提示';
      var content = "<div class='tccCon_d' style='padding:0 15px;'>您的问卷已收集 "+info.rspd_count+" 份数据，现在进行题目删改可能会影响已收集的数据。";
      content += "<br/><br/>在您修改问卷时，问卷会暂停收集，您需在修改完后再次发布问卷才可继续进行收集。<br/><br/></div>";
      confirm_popup_win.content = content;
      confirm_popup_win.obj = continue_design_project;
      confirm_popup_win.conw = 470;
      confirm_popup_win.obj_text = "确定";
      confirm_popup_win.close_text = "取消";
      jsConfirm(confirm_popup_win);
	  
	  $('.tccCon_d').jqTransform();
	  
    }
    else if(info.proj_status == 1)
    {
      var confirm_zero_win = Object;
      confirm_zero_win.title = '修改提示';
      var content_zero = "您修改问卷时，问卷会暂停收集，您需在修改完后再次发布问卷才可继续进行收集，原问卷链接不会改变。";
      confirm_zero_win.content = content_zero;
      confirm_zero_win.obj = continue_design_project_zero;
	    confirm_zero_win.conw = 470;
      confirm_zero_win.obj_text = "确定";
      confirm_zero_win.close_text = "取消";
      jsConfirm(confirm_zero_win);
    }
    else
    {
      location.href = "/edit/survey/"+$(cur_design_obj).attr("pid");
    }
  }
  else if(info.proj_status == 0)
  {
    location.href = "/edit/survey/"+$(cur_design_obj).attr("pid");
  }
  else if(info.proj_status == 1)
  {
    var confirm_zero_win = Object;
    confirm_zero_win.title = '修改提示';
    var content_zero = "您修改问卷时，问卷会暂停收集，您需在修改完后再次发布问卷才可继续进行收集，原问卷链接不会改变。";
    confirm_zero_win.content = content_zero;
    confirm_zero_win.obj = continue_design_project_zero;
	confirm_zero_win.conw = 470;
    confirm_zero_win.obj_text = "确定";
    confirm_zero_win.close_text = "取消";
    jsConfirm(confirm_zero_win);
  }
}
function do_nothing(){}

function continue_design_project_zero(){
  $.ajax({
        url: "/edit/ajax/update_project_status/",
        type: "POST",
        data: {"proj_id": $(cur_design_obj).attr("pid"), "status": 0, "_xsrf": $.cookie("_xsrf")},
        dataType: "JSON",
        success: function(ret) {
          location.href = "/edit/survey/"+$(cur_design_obj).attr("pid");
          }
        });
}

/*清空问卷数据,因为采用归档，故先注释*/
function clear_rspd_data(){
  $("#del_rspd_data").find('input[name="proj_id"]').val($(cur_design_obj).attr("pid"));
  ajaxSubmit($("#del_rspd_data"));
}

function update_rspd_count(info){
  if(info.rspd_count == 0)
  {
    $("#rspd_count_"+info.proj_id).text(info.rspd_count);
    $("#cleanup_"+info.proj_id).removeClass('color');
    $("#cleanup_"+info.proj_id).addClass("color_gray");
  }
}
/*继续编辑设计问卷*/
function continue_design_project(){
  $("#project_archive_form input[name='is_merge']").val(0);
  $("#project_archive_form").find('input[name="proj_id"]').val($(cur_design_obj).attr("pid"));
  ajaxSubmit($("#project_archive_form"));
}

function project_archive_form_callback(info){
  if(info.result == "Success")
    location.href = "/edit/survey/"+$(cur_design_obj).attr("pid");
}

function project_status_unchanged(obj) {
  obj.val(obj.attr("lastv"));
}

function del_project_callback(resultJson) {
  var $form = $("#form1");
  var curr_proj_id = $form.find('input[name="proj_id"]').val();
  if("page_index_del" == resultJson.type) {
    $(".deletebtn").each(function() {
      var curr_pid = $(this).attr("pid");
      if(curr_proj_id == curr_pid) {
        $(this).parent().parent().remove();
        // var lines_num = $("#proj_list tbody").children("tr").length;
        // if(lines_num < 7) {
          if(curr_page >= total_pages) {
            if(mid=='51dd234e9b9fbe6646bf4dd5')
              window.location.href = "/mysurvey?fld=created&page=" + total_pages;
            else
              window.location.href = "/mysurvey?page=" + total_pages;
          } else {
            if(mid=='51dd234e9b9fbe6646bf4dd5')
              window.location.href = "/mysurvey?fld=created&page=" + curr_page;
            else
              window.location.href = "/mysurvey?page=" + curr_page;
          }
        // }
        return;
      }
    });
  } else if("page_index_cleanup" == resultJson.type) {
    $(".alignc").each(function() {
      var curr_pid = $(this).attr("pid");
      if(curr_proj_id == curr_pid) {
        $(this).text(0);
        return;
      }
    })
  } else if("page_index_status_changed" == resultJson.type) {
    $(".surveytable table tbody tr td select").each(function() {
      var tmp_pid = $(this).attr("pid");
      if(curr_proj_id == tmp_pid) {
        var status = $(this).find("option:selected").val();
        $(this).attr("lastv", status);
        if(resultJson.shared && resultJson.shared == "True") {
          $(this).attr("is_shared", 1);
          $(this).attr("copy_from_pid", "True");
        }
        var curr_status = $(this).val();
        if(curr_status == 2) {
            var design_copy = $(this).parent().next().next().children().eq(0);
            design_copy.removeClass("editor").addClass("editorgray");
            design_copy.attr("href", "javascript:void(0);");
            var collect = $(this).parent().next().next().children().eq(1);
            collect.removeClass("collect").addClass("collectgray");
            collect.attr("href", "javascript:void(0);");
          }
          else{
            if(curr_status == 1)
            {
              loadMack({off:'on',text:'发布中',set:3000});
              setTimeout(function(){
                var design_copy = $(this).parent().next().next().children().eq(0);
                design_copy.attr("title", "问卷设计");
                design_copy.removeClass("editorgray").addClass("editor");
                design_copy.attr("href", "/edit/survey/" + curr_proj_id);
                var collect = $(this).parent().next().next().children().eq(1);
                collect.attr("href", "/collect/urllink/" + curr_proj_id);
                collect.removeClass("collectgray").addClass("collect");
              }, 3000);
            }
            else
            {
              var design_copy = $(this).parent().next().next().children().eq(0);
              design_copy.attr("title", "问卷设计");
              design_copy.removeClass("editorgray").addClass("editor");
              design_copy.attr("href", "/edit/survey/" + curr_proj_id);
              var collect = $(this).parent().next().next().children().eq(1);
              collect.attr("href", "/collect/urllink/" + curr_proj_id);
              collect.removeClass("collectgray").addClass("collect");
            }
          }
        return false;
      }
    });
  }
  $('#maptss').remove();
  $('#lightBox').remove();
}
